<template>
  <div class="data-visualization-container">
    <!-- 加载动画 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">
        <i class="el-icon-loading"></i>
        <p>数据加载中...</p>
      </div>
    </div>

    <!-- 主内容区 -->
    <div v-else class="content-wrapper">
      <!-- 左侧地图区域 60% -->
      <div class="left-panel">
        <div class="panel-header">
          <h3 class="panel-title">
            <i class="el-icon-location-outline"></i>
            地理分布数据
          </h3>
          <el-radio-group v-model="mapDataType" size="small" @change="handleMapTypeChange">
<!--            <el-radio-button label="user">用户分布</el-radio-button>-->
<!--            <el-radio-button label="video">视频分布</el-radio-button>-->
          </el-radio-group>
        </div>
        <div class="map-container" ref="mapContainer">
          <div id="chinaMap" ref="chinaMap"></div>
        </div>
        <div class="map-stats">
          <div class="stat-item">
            <div class="stat-label">总计</div>
            <div class="stat-value">{{ mapStats.total }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">区域数</div>
            <div class="stat-value">{{ mapStats.regions }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最高</div>
            <div class="stat-value">{{ mapStats.max }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧排行榜区域 40% -->
      <div class="right-panel">
        <div class="panel-header">
          <h3 class="panel-title">
            <i class="el-icon-star-off"></i>
            热度视频 TOP10
          </h3>
        </div>

        <!-- 无数据提示 -->
        <div v-if="hotVideos.length === 0" class="empty-data">
          <i class="el-icon-video-camera-solid"></i>
          <p>暂无视频数据</p>
          <el-button size="small" type="primary" @click="loadHotVideos">重新加载</el-button>
        </div>

        <!-- 排行榜列表 -->
        <div v-else class="ranking-container">
          <div class="ranking-list">
            <div
              v-for="(video, index) in hotVideos.slice(0, 10)"
              :key="video.id"
              class="ranking-item"
              :class="{ 'top-three': index < 3 }"
              @click="handleVideoClick(video)">
              <!-- 排名标识 -->
              <div class="rank-badge">
                <span v-if="index < 3" class="rank-icon">
                  <i class="el-icon-medal"></i>
                </span>
                <span v-else class="rank-number">{{ index + 1 }}</span>
              </div>

              <!-- 视频缩略图 -->
              <div class="video-cover">
                <el-image
                  :src="video.coverUrl"
                  fit="cover"
                  :preview-src-list="[video.coverUrl]">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>

              <!-- 视频信息 -->
              <div class="video-info">
                <div class="video-title" :title="video.title">{{ video.title }}</div>
                <div class="video-meta">
                  <span class="meta-item">
                    <i class="el-icon-user"></i>
                    {{ video.nickname || '未知用户' }}
                  </span>
                  <span class="meta-item">
                    <i class="el-icon-time"></i>
                    {{ formatDate(video.createdAt) }}
                  </span>
                </div>
                <!-- 观看和点赞统计 -->
                <div class="video-stats">
                  <span class="stat-item">
                    <i class="el-icon-view"></i>
                    {{ formatNumber(video.viewCount) }}
                  </span>
                  <span class="stat-item">
                    <i class="el-icon-thumb"></i>
                    {{ formatNumber(video.likeCount) }}
                  </span>
                </div>
              </div>

              <!-- 热度值 -->
              <div class="hot-value">
                <i class="el-icon-hot-water hot-icon"></i>
                <span class="hot-number">{{ formatHotValue(calculateHotValue(video)) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getMapData, getHotVideos } from '@/api/system/bigscreen'

export default {
  name: 'DataVisualization',
  data() {
    return {
      loading: true,
      mapDataType: 'user', // user 或 video
      mapChart: null,
      mapData: [],
      mapStats: {
        total: 0,
        regions: 0,
        max: 0
      },
      hotVideos: []
    }
  },
  mounted() {
    this.initPage()
  },
  beforeDestroy() {
    if (this.mapChart) {
      this.mapChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
      async initPage() {
        try {
          this.loading = true

          // 并行加载数据
          await Promise.all([
            this.loadMapData(),
            this.loadHotVideos()
          ])

          // 等待 DOM 更新
          await this.$nextTick()

          // 延迟初始化地图，确保DOM已完全渲染
          setTimeout(() => {
            this.initMap()
          }, 100)

          // 监听窗口大小变化
          window.addEventListener('resize', this.handleResize)

          this.loading = false
        } catch (error) {
          console.error('初始化页面失败:', error)
          this.$message.error('数据加载失败，请刷新重试')
          this.loading = false
        }
      },

      // 格式化数字显示
      formatNumber(num) {
        if (num >= 1000000) {
          return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
          return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
      },

      // 加载地图数据
    async loadMapData() {
      try {
        console.log('🌍 正在请求地图数据...', this.mapDataType)
        const response = await getMapData(this.mapDataType)
        console.log('✅ 地图数据返回:', response)
        this.mapData = response.data || []

        // 计算统计数据
        this.mapStats.total = this.mapData.reduce((sum, item) => sum + item.value, 0)
        this.mapStats.regions = this.mapData.length
        this.mapStats.max = Math.max(...this.mapData.map(item => item.value), 0)
        console.log('📊 地图统计:', this.mapStats)
      } catch (error) {
        console.error('❌ 加载地图数据失败:', error)
        this.mapData = []
      }
    },

    // 加载热度视频
    async loadHotVideos() {
      try {
        console.log('🔥 正在请求热度视频...')
        const response = await getHotVideos({ size: 10 })
        console.log('✅ 热度视频返回:', response)
        this.hotVideos = response.rows || response.data || []
        console.log('📺 视频数量:', this.hotVideos.length)
      } catch (error) {
        console.error('❌ 加载热度视频失败:', error)
        console.error('详细错误:', error.response || error.message)
        this.hotVideos = []
      }
    },

    // 初始化地图
    async initMap() {
      if (!this.$refs.chinaMap) {
        console.warn('⚠️ 地图容器未找到')
        return
      }

      console.log('🗺️ 开始初始化地图...')

      // 加载中国地图数据（使用在线资源）
      try {
        console.log('📥 正在加载中国地图JSON...')
        const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
        const chinaJson = await response.json()
        console.log('✅ 地图JSON加载成功')

        echarts.registerMap('china', chinaJson)
        console.log('✅ 地图已注册到ECharts')

        this.mapChart = echarts.init(this.$refs.chinaMap)
        console.log('✅ ECharts实例已创建')

        this.updateMapChart()
        console.log('✅ 地图已渲染')
      } catch (error) {
        console.error('❌ 加载地图数据失败:', error)
        this.$message.error('地图数据加载失败，请检查网络连接')
      }
    },

    // 更新地图图表
    updateMapChart() {
      if (!this.mapChart) {
        console.warn('⚠️ ECharts实例不存在，无法更新地图')
        return
      }

      console.log('🎨 开始更新地图，数据条数:', this.mapData.length)
      console.log('📊 地图数据详情:', JSON.stringify(this.mapData, null, 2))

      // 检查容器尺寸
      const container = this.$refs.chinaMap
      console.log('📏 地图容器尺寸:', {
        width: container.offsetWidth,
        height: container.offsetHeight
      })

      const option = {
        backgroundColor: '#fff',
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            if (params.data) {
              const type = this.mapDataType === 'user' ? '用户数' : '视频数'
              return `${params.name}<br/>${type}: ${params.data.value}`
            }
            return params.name
          }
        },
        visualMap: {
          min: 0,
          max: this.mapStats.max || 100,
          text: ['高', '低'],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
          },
          textStyle: {
            color: '#333'
          },
          left: 'left',
          top: 'bottom'
        },
        series: [
          {
            name: this.mapDataType === 'user' ? '用户分布' : '视频分布',
            type: 'map',
            map: 'china',
            roam: true,
            aspectScale: 0.75,
            zoom: 1.2,
            label: {
              show: true,
              fontSize: 10,
              color: '#333'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                color: '#fff'
              },
              itemStyle: {
                areaColor: '#1890ff',
                borderColor: '#fff',
                borderWidth: 2
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1,
              areaColor: '#eee'
            },
            data: this.mapData
          }
        ]
      }

      console.log('⚙️ 地图配置:', option)
      console.log('⚙️ 地图series数据:', option.series[0].data.slice(0, 3))

      this.mapChart.setOption(option, true)
      console.log('✅ 地图配置已应用')

      // 强制重绘
      setTimeout(() => {
        this.mapChart.resize()
        console.log('✅ 地图已重绘，最终尺寸:', {
          width: this.mapChart.getWidth(),
          height: this.mapChart.getHeight()
        })
      }, 200)
    },

    // 切换地图数据类型
    async handleMapTypeChange() {
      console.log('🔄 切换地图类型:', this.mapDataType)
      this.loading = true
      await this.loadMapData()

      // 等待DOM更新
      await this.$nextTick()

      if (this.mapChart) {
        this.updateMapChart()
      } else {
        console.warn('地图实例不存在，重新初始化')
        await this.initMap()
      }

      this.loading = false
    },



    // 处理视频点击
    handleVideoClick(video) {
      // this.$message.info(`点击了视频: ${video.title}`)
      // 可以在这里跳转到视频详情页
      // this.$router.push({ path: '/video/detail', query: { id: video.id } })
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      const d = new Date(date)
      const now = new Date()
      const diff = now - d
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) return '今天'
      if (days === 1) return '昨天'
      if (days < 7) return `${days}天前`
      return `${d.getMonth() + 1}-${d.getDate()}`
    },

    // 格式化热度值
    formatHotValue(value) {
      if (!value) return 0
      if (value >= 10000) {
        return (value / 10000).toFixed(1) + 'w'
      }
      return value
    },

    // 计算视频热度值
    calculateHotValue(video) {
      if (!video) return 0
      // 简单的热度计算公式：观看次数 + 点赞次数 * 2 + 评论次数 * 3
      const viewCount = video.viewCount || 0
      const likeCount = video.likeCount || 0
      const commentCount = video.commentCount || 0
      return viewCount + likeCount * 2 + commentCount * 3
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.mapChart) {
        this.mapChart.resize()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.data-visualization-container {
  width: 100%;
  height: calc(100vh - 84px);
  background: #f0f2f5;
  position: relative;
  overflow: hidden;

  // 加载动画
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.95);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .loading-spinner {
      text-align: center;

      i {
        font-size: 48px;
        color: #409eff;
        animation: rotate 1.5s linear infinite;
      }

      p {
        margin-top: 16px;
        font-size: 16px;
        color: #666;
      }
    }
  }

  // 主内容区
  .content-wrapper {
    display: flex;
    height: 100%;
    padding: 20px;
    gap: 20px;
    animation: fadeIn 0.8s ease-in;
  }

  // 左侧面板
  .left-panel {
    flex: 0 0 60%;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    padding: 24px;
    display: flex;
    flex-direction: column;
  }

  // 右侧面板
  .right-panel {
    flex: 0 0 calc(40% - 20px);
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    padding: 24px;
    display: flex;
    flex-direction: column;
  }

  // 面板头部
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 2px solid #e8e8e8;

    .panel-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      display: flex;
      align-items: center;
      gap: 8px;

      i {
        font-size: 22px;
        color: #1890ff;
      }
    }
  }

  // 地图容器
  .map-container {
    flex: 1;
    position: relative;
    min-height: 400px;
    height: 100%;

    #chinaMap {
      width: 100%;
      height: 100%;
      min-height: 400px;
    }
  }

  // 地图统计
  .map-stats {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e8e8e8;

    .stat-item {
      text-align: center;
      flex: 1;

      .stat-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #1890ff;
      }
    }
  }

  // 无数据提示
  .empty-data {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;

    i {
      font-size: 64px;
      color: #ddd;
      margin-bottom: 16px;
    }

    p {
      font-size: 14px;
      margin-bottom: 16px;
    }
  }

  // 排行榜容器
    .ranking-container {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      position: relative;
      background: #fafafa;
      border-radius: 8px;
      padding: 16px 12px;

      // 自定义滚动条样式
      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;

        &:hover {
          background: #a8a8a8;
        }
      }
    }

    .ranking-list {
      transition: transform 0.3s ease;
    }

    // 排行榜项
    .ranking-item {
      display: flex;
      align-items: center;
      background: #fff;
      border-radius: 8px;
      padding: 12px 16px;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
      border: 1px solid #f0f0f0;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }

      &.top-three {
        background: linear-gradient(90deg, #fffbe6 0%, #fff 100%);
        border-left: 4px solid #faad14;

        .rank-badge {
          background: linear-gradient(135deg, #faad14 0%, #fa8c16 100%);
          color: #fff;
        }
      }

      // 排名徽章
      .rank-badge {
        flex: 0 0 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: #f0f0f0;
        margin-right: 16px;
        font-weight: 600;
        color: #666;
        font-size: 14px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

        .rank-icon {
          font-size: 16px;
          color: #fff;
        }

        .rank-number {
          font-size: 14px;
        }
      }

      // 视频封面
      .video-cover {
        flex: 0 0 70px;
        height: 50px;
        border-radius: 6px;
        overflow: hidden;
        margin-right: 16px;
        position: relative;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

        ::v-deep .el-image {
          width: 100%;
          height: 100%;
        }

        .image-slot {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
          color: #999;
          font-size: 20px;
        }

        .cover-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.4);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s;

          i {
            font-size: 24px;
            color: #fff;
          }
        }

        &:hover .cover-overlay {
          opacity: 1;
        }
      }

      // 视频信息
      .video-info {
        flex: 1;
        min-width: 0;
        margin-right: 16px;

        .video-title {
          font-size: 15px;
          font-weight: 500;
          color: #333;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          line-height: 1.4;
        }

        .video-meta {
            display: flex;
            gap: 16px;
            font-size: 12px;
            color: #999;

            .meta-item {
              display: flex;
              align-items: center;
              gap: 4px;

              i {
                color: #999;
                font-size: 13px;
              }
            }
          }

          // 视频统计
          .video-stats {
            display: flex;
            gap: 12px;
            margin-top: 8px;
            font-size: 12px;
            color: #666;

            .stat-item {
              display: flex;
              align-items: center;
              gap: 4px;

              i {
                color: #409eff;
                font-size: 12px;
              }
            }
          }
      }

      // 热度值
      .hot-value {
        flex: 0 0 auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;

        .hot-icon {
          font-size: 18px;
          color: #ff4d4f;
        }

        .hot-number {
          font-size: 15px;
          font-weight: 600;
          color: #ff4d4f;
        }
      }
    }
}

// 动画
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式适配
@media screen and (max-width: 1440px) {
  .data-visualization-container {
    .content-wrapper {
      flex-direction: column;

      .left-panel,
      .right-panel {
        flex: 1;
        width: 100%;
      }
    }
  }
}
</style>

